//
//  YDPhotoAssetBrower.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/8/11.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import MVVM_BaseViewController
import Photos
import RxCocoa
import RxSwift
import YD_Util

class YDPhotoAssetBrower: MVVM_BaseViewController, UIScrollViewDelegate {
    
    let photoScrollView = UIScrollView()
    let photoImageView = UIImageView()
    
    var currentVCModel:YDPhotoAssetBrowerVCModel {
        get{
            return vcModel.value as! YDPhotoAssetBrowerVCModel
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    

    
    override func setupUI() {
        photoScrollView.frame = view.bounds
        photoImageView.frame = view.bounds
        photoImageView.contentMode = .scaleAspectFit
        photoScrollView.contentSize = CGSize.init(width: view.bounds.width, height: view.bounds.height)
        photoScrollView.addSubview(photoImageView)
        view.addSubview(photoScrollView)
        
        
        view.backgroundColor = UIColor.black
        
        //zoom
        photoScrollView.delegate = self
        photoScrollView.maximumZoomScale = 2.0
        let doubleTap = UITapGestureRecognizer()
        doubleTap.numberOfTapsRequired = 2
        
        doubleTap.rx.event.bindNext { [unowned self] (x: UITapGestureRecognizer) in
                if (self.photoScrollView.zoomScale > 1) {
                    self.photoScrollView.setZoomScale(1, animated: true)
                } else {
                    let point = x.location(in: self.photoScrollView)
                    let side_zoomToRect:CGFloat = 80
                   let rect = CGRect.init(x: point.x - side_zoomToRect / CGFloat(2), y:point.y - side_zoomToRect / CGFloat(2), width:side_zoomToRect , height: side_zoomToRect)
                    self.photoScrollView.zoom(to: rect, animated: true)
                }
        }
        .addDisposableTo(disposeBag)
        
        let singleTap = UITapGestureRecognizer()
        singleTap.rx.event.bindNext { [unowned self](x: UITapGestureRecognizer) in
            self.currentVCModel.singleClick()
        }
        .addDisposableTo(disposeBag)
//
        singleTap.require(toFail: doubleTap)
        
       //设置 点击事件优先级
        photoScrollView.addGestureRecognizer(doubleTap)
        photoScrollView.addGestureRecognizer(singleTap)
    }
    
    
    override func bindModelData() {
        currentVCModel.orignalImage.asObservable()
            .bindNext {[unowned self] (x: UIImage?) in
           self.photoImageView.image = x
        }
        .addDisposableTo(disposeBag)
    }
    
    
    //MARK: image zoom
    
    
    //MARK:UIScrollViewDelegate
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return photoImageView
    }
}

class YDPhotoAssetBrowerVCModel: MVVM_BaseVCModel {
    
    var singleClickBlock: (() -> Void)?
    
    override func viewController(vcIndex: Int) -> MVVM_BaseViewController? {
        return YDPhotoAssetBrower()
    }
    
    
    var asset = Variable<PHAsset?>(nil)
    var orignalImage = Variable<UIImage?>(nil)
    var orignalImageSize = Variable<Int?>(nil)
    
    init(asset:PHAsset?) {
        self.asset.value = asset
        super.init(parentViewModel: nil)
    }
    
    func clean() {
        asset.value = nil
        orignalImage.value = nil
        orignalImageSize.value = nil
    }
    
    
    var requestID:PHImageRequestID?
    override func setupModel() {
        
        asset.asObservable()
            .bindNext {[unowned self] (x: PHAsset?) in
                if let x = x {
                    let option = PHImageRequestOptions()
                    option.isNetworkAccessAllowed = true
                    
                    PHImageManager.default().requestImage(for: x, targetSize: CGSize.init(width: 80, height: 80), contentMode: .aspectFill, options: option, resultHandler: {[unowned self] (img, info) in
                        self.orignalImage.value = img
                    })
                }
            }
            .addDisposableTo(disposeBag)
        
        orignalImage.asObservable()
            .bindNext {[unowned self] (x: UIImage?) in
            if x != nil {
                
                if self.requestID != nil{
                    return
                }
                
                let option = PHImageRequestOptions()
                option.isNetworkAccessAllowed = true
                
                if let asset = self.asset.value{
                   self.requestID = PHImageManager.default().requestImageData(for: asset, options: option, resultHandler: {[unowned self] (imgData, _, _, _) in
                        if let imgData = imgData{
                            printLog("data -- \(imgData) -- size -- \(imgData.count)")
                            self.orignalImageSize.value = imgData.count
                            self.orignalImage.value = UIImage(data: imgData)
                        }
                    })
                }
         
            }
        }
        .addDisposableTo(disposeBag)
    }
    
    
    //MARK:Interaction
    func singleClick(){
        singleClickBlock?()
    }
    
    
    deinit{
        if let x = requestID{
           PHImageManager.default().cancelImageRequest(x)
        }
    }
}
